#include "Music.h"

Music::Music(string *fileList, int nb, int ch) {
	FMOD_System_Create(&system);
	FMOD_System_Init(system, ch, FMOD_INIT_NORMAL, NULL);
	pos = 0;
	this->channel = ch;

	for ( int i = 0 ; i < nb ; i++ ) {
		FMOD_SOUND * temp;
		string tempFile = "Sounds/" + fileList[i] + ".ogg";
		res = FMOD_System_CreateSound(system, tempFile.c_str(), FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM | FMOD_LOOP_NORMAL, 0, &temp);

		if (res != FMOD_OK) {
			cout << "Impossible de charger " << tempFile << endl;
			exit(EXIT_FAILURE);
		}

		musics.push_back(temp);
	}
}

Music::Music(int ch) {
	FMOD_System_Create(&system);
	FMOD_System_Init(system, ch, FMOD_INIT_NORMAL, NULL);
	pos = 0;
	this->channel = ch;
}

void Music::addMusic(string music) {
	FMOD_SOUND * temp;
	string tempFile = "Sounds/" + music + ".ogg";
	res = FMOD_System_CreateSound(system, tempFile.c_str(), FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM | FMOD_LOOP_NORMAL, 0, &temp);

	if (res != FMOD_OK) {
		cout << "Impossible de charger " << tempFile << endl;
		exit(EXIT_FAILURE);
	}

	musics.push_back(temp);
}

void Music::setLoop() {
	FMOD_Sound_SetLoopCount(musics[pos], -1);
}

void Music::setUnloop() {
	FMOD_Sound_SetLoopCount(musics[pos], 1);
}

void Music::play(int music) {
	if ( ! (music < 0 || music > musics.size() - 1) ) {
		pos = music;
		FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, musics[pos], 0, NULL);
	}
}

void Music::switchPause() {
	FMOD_CHANNEL *canal;
	FMOD_BOOL etat;
	FMOD_System_GetChannel(system, pos, &canal);
	FMOD_Channel_GetPaused(canal, &etat);

	if (etat)
		FMOD_Channel_SetPaused(canal, 0);
	else
		FMOD_Channel_SetPaused(canal, 1);
}


void Music::stop() {
	FMOD_CHANNEL *canal;
	FMOD_System_GetChannel(system, pos, &canal);
	FMOD_Channel_Stop(canal);
}

bool Music::is_Playing() {

	FMOD_CHANNEL *canal;
	FMOD_BOOL temp;

	FMOD_System_Update(system);
	FMOD_System_GetChannel(system, pos, &canal);
	FMOD_Channel_IsPlaying(canal, &temp);

	if ( temp )
		return true;
	else
		return false;
}

void Music::reset() {
	for ( unsigned int i = 0 ; i < musics.size() ; i++ )
		FMOD_Sound_Release(musics[i]);

	musics.clear();

	pos = 0;
	channel = 0;

	FMOD_System_Close(system);
	FMOD_System_Release(system);
}

Music::~Music() {
}
